using log4net.Config;
using log4net;
using MethodTimer;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.Text.RegularExpressions;

namespace MethodTimerDemo01
{
    [Time]
    internal class Program
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(Program));
        static string solutionPath = @"F:\Study\朝夕教育视频课程\WPFLesson\MethodTimerDemo01";
        //static string solutionPath = @"F:\Work-Git\WCS2.1 - 测试性能\MainControl";
        static string timeAttribute = "[Time]\n";
        static void Main(string[] args)
        {
            // 初始化 log4net
            XmlConfigurator.Configure(new FileInfo("App.config"));


            List<string> files = Directory.GetFiles(solutionPath, "*.cs", SearchOption.AllDirectories).ToList();

            foreach (string file in files)
            {
                string content = File.ReadAllText(file);
                string updatedContent = AddTimeAttribute(content);
                if (content != updatedContent)
                {
                    File.WriteAllText(file, updatedContent);
                    Console.WriteLine($"Updated file: {file}");
                }
            }
            log.Info("Application started.");

            // 你的应用程序逻辑
            DoSomething();
            DoSomething1();

            log.Info("Application ended.");

            Console.ReadKey();
        }

        
        [Time]
private static void DoSomething()
        {
            log.Info("Doing something...");
            // 模拟一些耗时操作
            System.Threading.Thread.Sleep(2000);
            log.Info("Done doing something.");
        }

        [Time]
private static void DoSomething1()
        {
            log.Info("Doing something...");
            // 模拟一些耗时操作
            System.Threading.Thread.Sleep(2000);
            log.Info("Done doing something.");
        }

        static string AddTimeAttribute(string content)
        {
            // 匹配所有没有 [Time] 特性的方法定义，并捕获方法定义前的缩进
            string pattern = @"(?<!\[Time\]\s*)(\s*)(\b(private|protected|internal|public)\s+static\s+void\s+\w+\s*\([^\)]*\)\s*\{)";
            return Regex.Replace(content, pattern, m => $"{m.Groups[1].Value}{timeAttribute}{m.Groups[2].Value}", RegexOptions.Multiline);
        }
    }

    public static class MethodTimeLogger
    {
        //按时段输出
        //public static void Log(MethodBase methodBase, TimeSpan elapsed, string message)
        //{
        //    Console.WriteLine($"方法：{methodBase.Name} 耗时(时段)：{elapsed}, 信息：{message}");
        //}

        //按总毫秒数输出
        [Time]
public static void Log(MethodBase methodBase, long milliseconds, string message)
        {
            Console.WriteLine($"方法：{methodBase.Name} 耗时(总毫秒数)：{milliseconds}, 信息：{message}");
        }
    }
}
